package com.xiaolin.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class dbUtils {
    private static Connection conn;
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        try {
            readinfo();                   //读取配置文件
            Class.forName(driver);        //反射的方式注册驱动
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            throw new RuntimeException("数据库链接失败！");
        }
    }

    //获取链接方式
    public static Connection getConnection() {
        System.out.println(conn);
        return conn;
    }

    public static void main(String[] args) {
        System.out.println(conn);
    }

    //关闭有结果集的资源
    public static void close(Connection conn, Statement ps, ResultSet rs) {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //关闭无结果集的资源
    public static void close(Connection conn, Statement ps) {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //读取配置文件
    private static void readinfo() throws IOException {
        InputStream is = dbUtils.class.getClassLoader().getResourceAsStream("dbutils.properties");
        //创建键所对应的值，并且赋值
        Properties pro = new Properties();
        pro.load(is);
        //赋值
        driver = pro.getProperty("driverClass");
        url = pro.getProperty("url");
        username = pro.getProperty("user");
        password = pro.getProperty("password");
        is.close();
    }
}
